# -*- coding:utf-8 -*-

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer, AcceptConnection, DenyConnection
from asgiref.sync import async_to_sync
import json

from django.core.cache import cache
import logging

logger = logging.getLogger("django")


class skUserView(WebsocketConsumer):
    """
    发送同步菜单，同步退出登陆
    """

    # groups 记录当前登陆的用户
    # groups = ["admin1", "admin2"]

    def websocket_connect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")

        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

        try:
            self.connect()
        except AcceptConnection:
            self.accept()
        except DenyConnection:
            self.close()

    def websocket_disconnect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        raise StopConsumer()

    def websocket_receive(self, message):
        """
        Called when a WebSocket frame is received. Decodes it and passes it
        to receive().
        """
        if "text" in message:
            # self.receive(text_data=message["text"])
            logger.info(message["text"])
        else:
            # self.receive(bytes_data=message["bytes"])
            logger.info(message["bytes"])

    def sendMsg(self, event):
        text = event["text"]
        logger.info(text)
        self.send(text)
        """
        {"isLogin":true,"menu":""}
        """


"""
视图中调用

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

channel_layer = get_channel_layer()


# LoginMsg

def send_msg(user_id, text):
    async_to_sync(channel_layer.group_send)(user_id, {"type": "sendMsg", "text": text})

"""
